package com.shinewind.task.timer;

import com.shinewind.pojo.vo.NewsVo;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class CarouselDataTask {
    @XxlJob("insertCarouselData")
    public void insertCarouselData() throws IOException {
        List<NewsVo> CarouselList = this.insertData("https://www.78dm.net/",
                "swiper-wrapper");
    }

    public static List<NewsVo> insertData(String url, String divId) throws IOException {
        //如果查询的是中文，需要转义
        Document document = Jsoup.parse(new URL(url),3000);
        //js中的方法都可以通过document对象调用
        Elements hrefList = document.getElementsByClass(divId).eq(0).select("a[href]");
        Elements srcList = document.getElementsByClass(divId).eq(0).select("a[href]").select("img[data-src]");
        Elements titleList = document.getElementsByClass(divId).eq(0).select("a[href]").select("div.banner-foot");

        List<NewsVo> newsVos = new ArrayList<>();
        //获取属性
        for(int i=0 ;i<5;i++){
            String hrefStr = hrefList.get(i).attr("href").trim();
            System.out.println("href:" + hrefStr);

            String srcStr = "https:"+srcList.get(i).attr("data-src").trim();
            System.out.println("src:" + srcStr);

            String titleStr = titleList.get(i).text().trim();
            System.out.println("title:" + titleStr+"\n");

            NewsVo newsVo = NewsVo.builder()
                    .title(titleStr)
                    .src(srcStr)
                    .href(hrefStr)
                    .build();
            newsVos.add(newsVo);
        }
        return newsVos;
    }
}
